import os
import tkinter as tk
from tkinter import ttk, messagebox
from language_manager import LanguageManager
from plugin_manager import PluginManager

class LanguageManagerWindow:
    """语言管理窗口"""
    def __init__(self, parent, lang_dir, selection_callback, close_callback):
        self.parent = parent
        self.lang_dir = lang_dir
        self.selection_callback = selection_callback
        self.close_callback = close_callback
        self.language_changed = False
        
        self.window = tk.Toplevel(parent)
        self.window.title("语言选择")
        self.window.geometry("400x300")
        self.window.transient(parent)
        self.window.grab_set()
        
        self._create_widgets()
        self._load_languages()
        
        # 窗口关闭时回调
        self.window.protocol("WM_DELETE_WINDOW", self._on_close)
    
    def _create_widgets(self):
        """创建窗口组件"""
        # 语言列表
        frame = ttk.Frame(self.window)
        frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        self.language_listbox = tk.Listbox(frame, selectmode=tk.SINGLE, width=40, height=10)
        self.language_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        scrollbar = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=self.language_listbox.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.language_listbox.config(yscrollcommand=scrollbar.set)
        
        # 按钮区域
        button_frame = ttk.Frame(self.window)
        button_frame.pack(fill=tk.X, padx=10, pady=10)
        
        self.enable_button = ttk.Button(button_frame, text="启用", command=self._enable_language)
        self.enable_button.pack(side=tk.LEFT, padx=5)
        
        self.disable_button = ttk.Button(button_frame, text="禁用", command=self._disable_language)
        self.disable_button.pack(side=tk.LEFT, padx=5)
        
        self.close_button = ttk.Button(button_frame, text="关闭", command=self._on_close)
        self.close_button.pack(side=tk.RIGHT, padx=5)
    
    def _load_languages(self):
        """加载语言文件"""
        self.language_listbox.delete(0, tk.END)
        
        if not os.path.exists(self.lang_dir):
            return
        
        # 首先加载已启用的语言
        for item in sorted(os.listdir(self.lang_dir)):
            if item.endswith('.lang') and not item.endswith('.disabled'):
                lang_name = item.replace('.lang', '')
                self.language_listbox.insert(tk.END, f"[启用] {lang_name}")
        
        # 然后加载已禁用的语言
        for item in sorted(os.listdir(self.lang_dir)):
            if item.endswith('.disabled') and item.endswith('.lang.disabled'):
                lang_name = item.replace('.lang.disabled', '')
                self.language_listbox.insert(tk.END, f"[禁用] {lang_name}")
    
    def _enable_language(self):
        """启用选中的语言"""
        selected_indices = self.language_listbox.curselection()
        if not selected_indices:
            messagebox.showinfo("提示", "请选择要启用的语言")
            return
        
        item = self.language_listbox.get(selected_indices[0])
        if item.startswith("[启用]"):
            messagebox.showinfo("提示", f"{item[5:]} 已经是当前启用的语言")
            return
        
        lang_name = item[5:].strip()
        language_file = f"{lang_name}.lang.disabled"
        self.language_changed = self.selection_callback(language_file)
        self._load_languages()
    
    def _disable_language(self):
        """禁用选中的语言"""
        selected_indices = self.language_listbox.curselection()
        if not selected_indices:
            messagebox.showinfo("提示", "请选择要禁用的语言")
            return
        
        item = self.language_listbox.get(selected_indices[0])
        if item.startswith("[禁用]"):
            messagebox.showinfo("提示", f"{item[5:]} 已经是禁用状态")
            return
        
        lang_name = item[5:].strip()
        old_path = os.path.join(self.lang_dir, f"{lang_name}.lang")
        new_path = os.path.join(self.lang_dir, f"{lang_name}.lang.disabled")
        try:
            os.rename(old_path, new_path)
            self.language_changed = True
            self._load_languages()
        except Exception as e:
            messagebox.showerror("错误", f"禁用语言失败: {str(e)}")
    
    def _on_close(self):
        """窗口关闭处理"""
        # 通知主程序语言是否已更改
        if self.close_callback:
            self.close_callback(self.language_changed)
        
        self.window.destroy()

class PluginManagerWindow:
    """插件管理窗口"""
    def __init__(self, parent, plugin_dir, restart_callback):
        self.parent = parent
        self.plugin_dir = plugin_dir
        self.restart_callback = restart_callback
        self.plugin_state_changed = False
        
        self.window = tk.Toplevel(parent)
        self.window.title("插件管理")
        self.window.geometry("600x400")
        self.window.transient(parent)
        self.window.grab_set()
        
        self._create_widgets()
        self._load_plugins()
        
        # 窗口关闭时检查是否需要提示重启
        self.window.protocol("WM_DELETE_WINDOW", self._on_close)
    
    def _create_widgets(self):
        """创建窗口组件"""
        # 插件列表
        frame = ttk.Frame(self.window)
        frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        self.plugin_listbox = tk.Listbox(frame, selectmode=tk.EXTENDED, width=50, height=15)
        self.plugin_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        scrollbar = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=self.plugin_listbox.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.plugin_listbox.config(yscrollcommand=scrollbar.set)
        
        # 按钮区域
        button_frame = ttk.Frame(self.window)
        button_frame.pack(fill=tk.X, padx=10, pady=10)
        
        self.enable_button = ttk.Button(button_frame, text="启用插件", command=self._enable_plugin)
        self.enable_button.pack(side=tk.LEFT, padx=5)
        
        self.disable_button = ttk.Button(button_frame, text="禁用插件", command=self._disable_plugin)
        self.disable_button.pack(side=tk.LEFT, padx=5)
        
        self.refresh_button = ttk.Button(button_frame, text="刷新列表", command=self._load_plugins)
        self.refresh_button.pack(side=tk.LEFT, padx=5)
        
        self.close_button = ttk.Button(button_frame, text="关闭", command=self._on_close)
        self.close_button.pack(side=tk.RIGHT, padx=5)
    
    def _load_plugins(self):
        """加载插件列表"""
        self.plugin_listbox.delete(0, tk.END)
        
        if not os.path.exists(self.plugin_dir):
            return
        
        # 首先加载已启用的插件
        for item in sorted(os.listdir(self.plugin_dir)):
            if item.endswith('.json') and not item.endswith('.disabled'):
                self.plugin_listbox.insert(tk.END, f"[启用] {item}")
        
        # 然后加载已禁用的插件
        for item in sorted(os.listdir(self.plugin_dir)):
            if item.endswith('.disabled'):
                self.plugin_listbox.insert(tk.END, f"[禁用] {item[:-9]}")
    
    def _enable_plugin(self):
        """启用选中的插件"""
        selected_indices = self.plugin_listbox.curselection()
        if not selected_indices:
            messagebox.showinfo("提示", "请选择要启用的插件")
            return
        
        for i in selected_indices:
            item = self.plugin_listbox.get(i)
            if item.startswith("[禁用]"):
                plugin_name = item[5:].strip()
                old_path = os.path.join(self.plugin_dir, f"{plugin_name}.disabled")
                new_path = os.path.join(self.plugin_dir, plugin_name)
                
                try:
                    os.rename(old_path, new_path)
                    messagebox.showinfo("成功", f"插件 {plugin_name} 已启用")
                    self.plugin_state_changed = True
                except Exception as e:
                    messagebox.showerror("错误", f"启用插件失败: {str(e)}")
        
        self._load_plugins()
    
    def _disable_plugin(self):
        """禁用选中的插件"""
        selected_indices = self.plugin_listbox.curselection()
        if not selected_indices:
            messagebox.showinfo("提示", "请选择要禁用的插件")
            return
        
        for i in selected_indices:
            item = self.plugin_listbox.get(i)
            if item.startswith("[启用]"):
                plugin_name = item[5:].strip()
                old_path = os.path.join(self.plugin_dir, plugin_name)
                new_path = os.path.join(self.plugin_dir, f"{plugin_name}.disabled")
                
                try:
                    os.rename(old_path, new_path)
                    messagebox.showinfo("成功", f"插件 {plugin_name} 已禁用")
                    self.plugin_state_changed = True
                except Exception as e:
                    messagebox.showerror("错误", f"禁用插件失败: {str(e)}")
        
        self._load_plugins()
    
    def _on_close(self):
        """窗口关闭处理"""
        if self.plugin_state_changed:
            response = messagebox.askyesno(
                "重启提示", 
                "插件配置已更改，需要重启程序以使更改生效。是否立即重启？",
                parent=self.window
            )
            if response:
                self.window.destroy()
                self.restart_callback()
            else:
                self.window.destroy()
        else:
            self.window.destroy()
